/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mx.netbrain.conversors;
  
import java.util.ArrayList;  
import java.util.List;  
import javax.faces.application.FacesMessage;  
  
import javax.faces.component.UIComponent;  
import javax.faces.context.FacesContext;  
import javax.faces.convert.Converter;  
import javax.faces.convert.ConverterException; 
import mx.netbrain.dao.OrganizationDao;
import mx.netbrain.dao.impl.OrganizationDaoImpl;
import mx.netbrain.model.Organization;
/**
 *
 * @author gamma
 */
public class OrganizationConverter implements Converter{
    
    public static List<Organization> listOrganization;
    public static OrganizationDao organizationDao = new OrganizationDaoImpl();
    
    static{
        listOrganization = organizationDao.listAll();
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if(value.trim().equals("")){
            return null;
        }else {
            try{
                Long identifier = Long.parseLong(value);
                for (Organization o : listOrganization){
                    if(identifier.equals(o.getId())){
                        return o;
                    }
                }
            }catch (NumberFormatException e){
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error de Conversión", "Empresa no válida"));
            }
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if(value == null || value.equals("")){
            return "";
        } else {
            return String.valueOf(((Organization) value).getId());
        }
    }
    
}
